﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.Design;

namespace MvcImproved.Generic
{
	// Custom ControlBuilder that instantiates the generic control when the page
	// is constructed.
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
	public class GenericControlTypeAttribute : Attribute
	{
		public Type GenericControl
		{
			get;
			private set;
		}
		public string GenericParameters = "GenericParameters";
		//MemberValue will always come immediately before SubMemberValue, or last if there is no SubMemberValue
		public string MemberValue = null;

		//SubMemberValue will always use last type in generic parameter list
		public string SubMemberValue = null;

		public GenericControlTypeAttribute(Type genericControl)
		{
			GenericControl = genericControl;
		}

		public string GetReferencedLambda(IDictionary attribs)
		{
			if ((!String.IsNullOrEmpty(MemberValue)) && attribs.Contains(MemberValue))
				return ((string)attribs[MemberValue]);
			return null;
		}

		public string GetReferencedSubMemberLambda(IDictionary attribs)
		{
			if ((!String.IsNullOrEmpty(SubMemberValue)) && attribs.Contains(SubMemberValue))
				return ((string)attribs[SubMemberValue]);
			return null;
		}

		internal List<Type> GenericArgumentList(IDictionary attribs, bool inDesigner, IServiceProvider serviceProvider)
		{
			return GenericArgumentList((string)attribs[GenericParameters], inDesigner, serviceProvider);
		}

		internal List<Type> GenericArgumentList(string list, bool inDesigner, IServiceProvider serviceProvider)
		{
			Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
			ITypeResolutionService resolutionService = null;
			if (inDesigner)
				resolutionService = serviceProvider.GetService(typeof(ITypeResolutionService)) as ITypeResolutionService;

			return (from typeName in list.Split(';') select Type.GetType(typeName, false) ?? ((resolutionService != null) ? resolutionService.GetType(typeName, true) : System.Web.Compilation.BuildManager.GetType(typeName, true))).ToList();
		}
	}
}
